import 'package:cloud_medicine/components/InputButtomWidget.dart';
import 'package:cloud_medicine/components/PopRoute.dart';
import 'package:cloud_medicine/components/author_show.dart';
import 'package:cloud_medicine/components/favorite_icon.dart';
import 'package:cloud_medicine/components/util.dart';
import 'package:cloud_medicine/http/comment_api.dart';
import 'package:cloud_medicine/http/config.dart';
import 'package:cloud_medicine/model/comment_info.dart';
import 'package:cloud_medicine/model/comment_item_info.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

// 帖子模块的评论显示
class CommentShow extends StatefulWidget {
  final int postID;

  CommentShow({Key key, @required this.postID}) : super(key: key);

  @override
  _CommentShowState createState() => _CommentShowState();
}

class _CommentShowState extends State<CommentShow> {
  bool _loading = false;
  CommentInfo _commentInfo;

  @override
  void initState() {
    super.initState();
    _init();
  }

  Widget _childLayout() {
    if (_loading) {
      return Center(
        child: Container(
          child: CircularProgressIndicator(),
        ),
      );
    } else {
      return Container(
          margin: EdgeInsets.only(top: 10),
          color: Colors.white,
          child: ListView(
            physics: new NeverScrollableScrollPhysics(),
            shrinkWrap: true,
            children: <Widget>[
              Container(
                  padding: EdgeInsets.all(8),
                  margin: EdgeInsets.only(left: 8, right: 8),
                  decoration: BoxDecoration(
                      border: Border(
                          bottom:
                              BorderSide(width: 1, color: Color(0xffe5e5e5)))),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text(
                        "相关评论(${_commentInfo.comment_num})",
                        style: TextStyle(color: Colors.grey, fontSize: 20),
                      ),
                      RaisedButton(
                        color: Colors.lightBlueAccent,
                        textColor: Colors.white,
                        onPressed: () {
                          // 弹出底部输入框
                          Navigator.push(context,
                              PopRoute(child: InputButtomWidget(
                            onEditingCompleteText: (text) {
                              _submit(text);
                            },
                          )));
                        },
                        child: Text('发表评论'),
                      )
                    ],
                  )),
              Container(
                padding: EdgeInsets.only(left: 8, right: 8, bottom: 8),
                child: ListView.builder(
                    itemCount: _commentInfo.data.length,
                    physics: new NeverScrollableScrollPhysics(),
                    shrinkWrap: true,
                    itemBuilder: (context, index) {
                      return generateCommentItemShow(_commentInfo.data[index]);
                    }),
              )
            ],
          ));
    }
  }

  // 生成每一条评论
  Widget generateCommentItemShow(CommentItemInfo commentItemInfo) {
    return ListView(
      physics: new NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      children: <Widget>[
        SizedBox(height: 8),
        AuthorShow(
          userID: commentItemInfo.authorBasicInfo.id,
          imageStyle: 40,
          avatar: commentItemInfo.authorBasicInfo.avatar,
          realname: commentItemInfo.authorBasicInfo.realname,
          createTime: commentItemInfo.createTime,
          widget: Row(
            children: <Widget>[
              FavoriteIcon(
                isLike: commentItemInfo.isLike,
                like_num: commentItemInfo.like_num.toString(),
                id: commentItemInfo.comment_id,
                isPost: false,
              ),
              SizedBox(width: 5),
              GestureDetector(
                onTap: () {
                  // 弹出底部输入框
                  Navigator.push(
                      context,
                      PopRoute(
                          child: InputButtomWidget(
                        placeholder:
                            '回复${commentItemInfo.authorBasicInfo.realname}：',
                        onEditingCompleteText: (text) {
                          print(text);
                          print(commentItemInfo.comment_id);
                          _submit(text,
                              parentCommentID: commentItemInfo.comment_id);
                        },
                      )));
                },
                child: Icon(Icons.comment, color: Colors.grey),
              )
            ],
          ),
        ),
        SizedBox(height: 10),
        Row(
          children: <Widget>[
            SizedBox(width: 45),
            Expanded(
              child: RichText(
                textAlign: TextAlign.left,
                text: TextSpan(
                    text: commentItemInfo.parentCommontRealname == null
                        ? ''
                        : '回复 ',
                    style: TextStyle(color: Colors.black),
                    children: <TextSpan>[
                      TextSpan(
                          text: commentItemInfo.parentCommontRealname == null
                              ? ''
                              : '${commentItemInfo.parentCommontRealname}',
                          style: TextStyle(color: Colors.blue)),
                      TextSpan(
                        text: commentItemInfo.parentCommontRealname == null
                            ? ''
                            : '：',
                      ),
                      TextSpan(text: commentItemInfo.content)
                    ]),
              ),
            )
          ],
        ),
        SizedBox(height: 8),
        Divider(
          height: 1,
        )
      ],
    );
  }

  // 增加评论
  Future<Null> _submit(String value, {int parentCommentID}) async {
    dynamic res = await addComment_api('$backIP/comment', {
      'postId': widget.postID,
      'content': value,
      'parentCommentID': parentCommentID,
    });
    if (res['code'] == 0) {
      _init();
    } else {
      errorToast(res['message']);
    }
  }

  // 初始化，获取帖子评论
  Future<Null> _init() async {
    setState(() {
      _loading = true;
    });
    dynamic res =
        await getComment_api('$backIP/comment/list', {'postId': widget.postID});
    if (res['code'] == 0) {
      if (mounted) {
        setState(() {
          _commentInfo = CommentInfo.init(res['data']);
        });
      }
    } else {
      errorToast(res['message']);
    }
    setState(() {
      _loading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return _childLayout();
  }
}
